#!/usr/bin/python
# -*- coding: cp1250 -*-

import pepe.p_sqlpg.txt2pg as txt2pg

from pepe.glib import *
from pepe.p_oslevel.system_variables import main as sv

def main(filemask):
    print '''
    import table to pg'''
    print '''    filemask = ''', filemask

    #username = sv('USERNAME')
    u = raw_input("""    Role (default is 'public'): """)
    if u == '':
        username = 'postgres'
    else:
        username = u[:]
    print '\n'

    for f in sorted(glob.glob(filemask)):

        print '    ', timenow(), f

        o = open(f, 'rb')
        line = o.readline()
        o.close()
    
        cd = findcoldelimiter_line(line)

        p = txt2pg.TxtImport()

        p.setInputDefaults()
        
        p.inputFileName = f
        p.colDelimiter = cd
        p.hasHeader = 1
        p.username = username[:]
        p.pgClientEncoding = 'UTF-8'

        p.setDeducedVariables()

        if 1: # scan file and create string
            p.queryCreateTable()
            #of = open('#create-and-load.sql', 'a')
            #of.write(p.queryCreateString)
            #of.close()

        if 1: # (modify query), create table and load data
            #p.queryCreateString = open('#c.sql', 'r').read()
            
            p.queryLoadTable()
            #of = open('#l.sql', 'w')
            #of.write(p.queryLoadString)
            #of.close()
            
            p.createTable()
            p.loadData()

        print '    ', timenow()

if __name__ == "__main__":
    """ """
    if len(sys.argv) > 1:
        main(sys.argv[1])
    else:
        print 'Wrong command syntax (argument is missing). Try again now.'
